package spring.config;

import java.util.EnumSet;

import javax.servlet.DispatcherType;
import javax.servlet.FilterRegistration;
import javax.servlet.FilterRegistration.Dynamic;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;

import org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter;
import org.springframework.orm.hibernate4.support.OpenSessionInViewFilter;
import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.ContextLoaderListener;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.filter.CharacterEncodingFilter;

public class WebInitializer implements WebApplicationInitializer {

    public void onStartup(ServletContext servletContext) throws ServletException {
    	Dynamic encodingfilter=servletContext.addFilter("encodingFilter", CharacterEncodingFilter.class);
    	encodingfilter.setInitParameter("encoding","UTF-8");
    	encodingfilter.addMappingForUrlPatterns(null, false, "/*");  
    	
        OpenSessionInViewFilter hibernateSessionInViewFilter = new OpenSessionInViewFilter();  
        FilterRegistration.Dynamic filterRegistration = servletContext.addFilter("hibernateFilter", hibernateSessionInViewFilter);
        filterRegistration.setInitParameter("singleSession", "true");
        filterRegistration.setInitParameter("flushMode", "auto");
        filterRegistration.addMappingForUrlPatterns(EnumSet.of(DispatcherType.REQUEST, DispatcherType.FORWARD, DispatcherType.INCLUDE), false, "/");  
    	
    	AnnotationConfigWebApplicationContext root = new AnnotationConfigWebApplicationContext();  
        root.register(DataSourceConfig.class);
        servletContext.addListener(new ContextLoaderListener(root));
        Dynamic filter=servletContext.addFilter("struts2", new StrutsPrepareAndExecuteFilter());
        filter.addMappingForUrlPatterns(null,false,"/*");
    }  
}
